package com.huawei.eidc.message;

import java.io.*;

//import org.apache.axis.client.Service;
import org.apache.axis.client.Service;
import org.apache.log4j.Logger;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;




public class WSDLServiceImpl //implements WSDLService 
{
	//webservice url
	public static final String $wsdl_url = "http://218.2.129.11:11070/ecagent/services/ECAgentService?wsdl";
	
	//xmlfile path
	public static final String reqXmlFilePath = "D:\\Developer\\Java\\WorkSpaceS\\Maven\\WorkSpace\\WebServices\\WebContent\\WEB-INF\\template\\";
	
	/**
     * 设置测试用密钥
     */
    public static final String TEST_KEY = "AD67EA2F3EE6E5AA";
    
	private static Logger logger = Logger.getLogger(WSDLServiceImpl.class);
	
//	public static final String $wsdl_url = DigesterParseXml.getXmlConfig().getServerMap().get("wsdl_url").toString();			
//	public static final String reqXmlFilePath = Path.getInstance().getWEBINF().replace("/",File.separator)+ File.separator+ "wsdl_xml"+ File.separator;

	
	public static void main(String[] args)
	{
		WSDLServiceImpl serviceImpl = new WSDLServiceImpl();
		serviceImpl.ECOrderQuery("xiangec1", "1");
		serviceImpl.ECOrderDetail("xiangec1");
		
	}

	//3.1.1		企业订购查询接口
	public String ECOrderQuery(String ECID,String STATE)
	{
		String interfaceMethod = "ECOrderQuery";
		String response = "";
		String reqXmlTemplate = getReqXmlTemplate(reqXmlFilePath+interfaceMethod+".xml"); 
		if(!"".equals("error"))
		{
			String reqXml = setReqXmlTemplate(reqXmlTemplate);
			if(!"".equals(reqXml))
			{
				response = requestSend(reqXml,"ecOrderQuery");
			}
		}		
		return response;
	}
	
	//3.1.2		企业订购详情查询接口
	public String ECOrderDetail(String ECORDERID)
	{
		String response = "";
		String reqXmlTemplate = getReqXmlTemplate(reqXmlFilePath+"ecOrderDetail"+".xml"); 
		if(!"".equals("error"))
		{
			String reqXml = setReqXmlTemplate(reqXmlTemplate);
			if(!"".equals(reqXml))
			{
				response = requestSend(reqXml,"ecOrderQuery");
			}
		}		
		return response;
	}
	
	/**
	 * 设置请求xml模板
	 * @param reqXmlTemplate
	 * @return
	 */
	public String setReqXmlTemplate(String reqXmlTemplate)
	{
		String reqXml = "";
		try
		{
			Document document = DocumentHelper.parseText(reqXmlTemplate);
			System.out.println("req:"+getXMLStr(document));
			/** HEAD SET
			Element head = document.getRootElement().element("HEAD");
			head.element("CODE").setText("");
			head.element("SID").setText("");
			head.element("TIMESTAMP").setText("");
			*/
			document = setReqXmlTemplateHead(document);
			System.out.println("head:"+getXMLStr(document));	
			
			
//			document = setReqXmlTemplateBody(document);						
//			System.out.println("body:"+getXMLStr(document));
			
		//	Element body = document.getRootElement().element("BODY");
		//	String encodeBodyPart = EncodeUtil.encrypt(getXMLStr(document), TEST_KEY);
			String bodyPart = getReqXmlTemplateBody();
			System.out.println("bodyPart:"+bodyPart);
			document.getRootElement().element("BODY").setText(bodyPart);
			
			//加密BODY 部分		
			
			
			//document.addElement("BODY").setText(bodyPart);
			System.out.println("req xml :"+getXMLStr(document));
			
			/** BODY SET
			Element body = document.getRootElement().element("BODY");
			Element pageinfo = body.element("PAGEINFO");
			pageinfo.element("CURRENTPAGE").setText("");
			pageinfo.element("PAGESIZE").setText("");
			
			body.element("ECID").setText("");
			body.element("STATE").setText("");
			*/
									
			reqXml = getXMLStr(document);
		}
		catch(Exception e)
		{
			logger.info("解析xml请求文件模板异常"+e.getMessage());
			return "exception";
		}
		return  reqXml;
		
	}
	
	
	/**
	 * 设置请求xml文件[HEAD ]部分
	 * @param document
	 * @return
	 * @throws DocumentException
	 */
	public Document setReqXmlTemplateHead(Document document) throws DocumentException
	{
		Element head = document.getRootElement().element("HEAD");
		head.element("CODE").setText("ECOrder");
		head.element("SID").setText("6786451");
		head.element("TIMESTAMP").setText("20120717110256333");
		
		return document;
	}
	
	/**
	 * 3.1.1	企业订购查询接口
	 * 设置请求xml[BODY]部分
	 * @param document
	 * @return
	 * @throws DocumentException
	 */
	public Document setReqXmlTemplateBody(Document document) throws DocumentException
	{
		Element body = document.getRootElement().element("BODY");
		Element pageinfo = body.element("PAGEINFO");
		pageinfo.element("CURRENTPAGE").setText("1");
		pageinfo.element("PAGESIZE").setText("5");
		
		body.element("ECID").setText("1000");
		body.element("STATE").setText("0");
		
		
		
		//加密BODY 部分
		EncodeUtil.encrypt(getXMLStr(document), TEST_KEY);
		return document;
	}
	
	
	public String getReqXmlTemplateBody() throws DocumentException
	{
        Document document = DocumentHelper.createDocument();
        
        Element body = document.addElement("BODY");
        Element pageinfo = body.addElement("PAGEINFO");
        pageinfo.addElement("CURRENTPAGE").addText("1");
        pageinfo.addElement("PAGESIZE").addText("5");
        body.addElement("ECID").addText("1000");
        body.addElement("STATE").addText("0");
        System.out.println();
        System.out.println("组织好的消息体XML文档：");
        System.out.println(getXMLStr(document));
		
		
		//加密BODY 部分		
		return EncodeUtil.encrypt(getXMLStr(document), TEST_KEY);
	}
	/**
	 * 3.1.2	企业订购详情查询接口
	 * 设置请求xml[BODY]部分
	 * @param document
	 * @return
	 * @throws DocumentException
	 
	public Document setReqXmlTemplateBody(Document document) throws DocumentException
	{
		Element body = document.getRootElement().element("BODY");		
		body.element("ECORDERID").setText("xiangec1");		
		return document;
	}
	*/
	
	
    /**
     * 传入XML格式的文档对象，返回转换为UTF8格式的字符串
     * @param document Document XML格式的文档对象
     * @return String 转换为UTF8格式的字符串
     */
    public static String getXMLStr(Document document)
    {
        try
        {
            java.io.StringWriter sw = new java.io.StringWriter();
            OutputFormat format = OutputFormat.createCompactFormat();
            format.setEncoding("UTF8");
            org.dom4j.io.XMLWriter xmlWriter = new org.dom4j.io.XMLWriter(sw,format);
            xmlWriter.write(document);
            xmlWriter.close();
            return sw.getBuffer().toString();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return "";
        }
    }
	
	/**
	 * 读取xml模板文件
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public static String getReqXmlTemplate(String filePath)
	{
		 StringBuffer sbuf = new StringBuffer();
		 try
		 { 
		      InputStream in = new FileInputStream(filePath); 
		      int  size=in.available();
		      for(int i=0;i<size;i++){
		       	 sbuf.append((char)in.read());      	  
		      }
			  in.close();	
		 }
		 catch (Exception e)
		 {
		      logger.info("读取xml请求文件模板异常:"+e.getMessage());
		      return "exception";
		 };  
		 return sbuf.toString().trim();
	}
	
	
	/**
	 * 发送请求
	 * @param reqXml
	 * @param method
	 * @return
	 */
	public static String requestSend(String reqXml ,String method)
	{
		String response = ""; 
				
				
	    try {
	    	
        	//String strTemp = util.getString("e:/1.txt");
        	//System.out.println("request:"+strTemp);
            String address = "http://218.2.129.11:11070/ecagent/services/ECAgentService?wsdl";
            //String address = "http://218.2.129.11:11070/ecagent/services";
            Service service = new org.apache.axis.client.Service();
            org.apache.axis.client.Call call = null;
            call = (org.apache.axis.client.Call) service.createCall();
            call.setOperationName(new javax.xml.namespace.QName(address, method));
            call.setTargetEndpointAddress(new java.net.URL(address));
            //String smg = strTemp;
            String ret = (String) call.invoke("ecOrderQuery",new Object[] {reqXml});
           
            System.out.println("response:"+ret);
	        
            Document document = DocumentHelper.parseText(ret);
            String strBody = document.getRootElement().element("BODY").getTextTrim();
            response = EncodeUtil.decrypt(strBody,TEST_KEY);
            System.out.println("response:"+response);
//            System.out.println("消息打包完成.");
//            System.out.println();
//
//            System.out.println("消息解包...");
//            System.out.println();
//
//            if ( EncodeUtil.decode(ret,TEST_KEY) ) {
//                System.out.println("decode OK!");
//            }
//            else {
//                System.out.println("decode ERROR!");
//            }
//            System.out.println("消息解包完成.");
	    } catch (Exception ex) {
	        ex.printStackTrace();
	    }
	    return response;
	}
	

}
